package com.hashcoding.eyes.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.hashcoding.eyes.R;
import com.hashcoding.eyes.data.constant.APIConstant;
import com.hashcoding.eyes.data.entity.Photo;
import com.hashcoding.eyes.data.entity.PhotosList;
import com.hashcoding.eyes.data.entity.User;
import com.hashcoding.eyes.data.entity.UserList;
import com.hashcoding.eyes.module.manager.LoginManager;
import com.hashcoding.eyes.module.utils.LogUtil;
import com.hashcoding.eyes.module.utils.ResourceUtil;
import com.hashcoding.eyes.ui.adapter.BaseListAdapter;
import com.hashcoding.eyes.ui.adapter.PhotosListAdapter;
import com.hashcoding.eyes.ui.protocol.IScrollListener;
import com.hashcoding.eyes.ui.view.EmptyLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

public class MainActivity extends BaseActivity implements AdapterView.OnItemClickListener,
        SwipeRefreshLayout.OnRefreshListener {

    @Bind(R.id.title_text)
    TextView mTitleText;
    @Bind(R.id.toolbar)
    RelativeLayout mToolbar;
    @Bind(R.id.list_view)
    ListView mListView;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;
    @Bind(R.id.error_layout)
    EmptyLayout mErrorLayout;
    @Bind(R.id.toolbar_bg_green)
    ImageView mToolbarBgGreen;
    @Bind(R.id.title_right_btn)
    ImageView mTitleRightBtn;
    @Bind(R.id.title_left_btn)
    ImageView mTitleLeftBtn;
    @Bind(R.id.avatar_view)
    ImageView mAvatarView;
    @Bind(R.id.left_list_view)
    ListView mLeftListView;
    @Bind(R.id.left_drawer)
    LinearLayout mLeftDrawer;
    @Bind(R.id.drawer_layout)
    DrawerLayout mDrawerLayout;
    @Bind(R.id.user_name)
    TextView mUserName;

    private PhotosListAdapter mAdapter;

    private long mLastExitTime;

    private int mLastID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        initView();
    }

    private void initView() {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setColorSchemeColors(
                ResourceUtil.getColorsByStringArray(this, R.array.ProgressColorArray));

        mErrorLayout.setState(EmptyLayout.STATE_EMPTY);
        mErrorLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refreshData();
            }
        });

        mAdapter = new PhotosListAdapter(this);

        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(this);
        mListView.setOnScrollListener(new IScrollListener() {
            @Override
            public void onLoadMore() {
                if (mAdapter.canLoadMore()) {
                    mAdapter.setState(BaseListAdapter.STATE_LOADING);
                    loadMore();
                }
            }
        });

        // Set the adapter for the list view
        mLeftListView.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_expandable_list_item_1, initMenu()));
        // Set the list's click listener
        mLeftListView.setOnItemClickListener(new DrawerItemClickListener());
        mDrawerLayout.closeDrawer(mLeftDrawer);

        try {
            User user = UserList.instance().get(LoginManager.instance().get());
            Glide.with(this).load(user.avatarURL)
                    .placeholder(R.drawable.head)
                    .bitmapTransform(new CenterCrop(this), new CropCircleTransformation(this))
                    .into(mAvatarView);
            mUserName.setText(user.name);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mAdapter.setList(new ArrayList<Photo>());

        refreshData();
    }

    private void refreshData() {
        mErrorLayout.setState(EmptyLayout.STATE_LOADING);
        mRefreshLayout.setRefreshing(true);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                // load data
                List<Photo> photos = PhotosList.instance().loadData();
                if (photos.size() == 0) {
                    mErrorLayout.setState(EmptyLayout.STATE_EMPTY);
                    mAdapter.setState(BaseListAdapter.STATE_NO_DATA);
                } else {
                    mAdapter.setList(photos);
                    mErrorLayout.setState(EmptyLayout.STATE_HIDE);
                    mAdapter.setState(photos.size() >= APIConstant.PAGE_COUNT
                            ? BaseListAdapter.STATE_LOAD_MORE
                            : BaseListAdapter.STATE_NO_MORE);
                    mLastID = photos.get(photos.size() - 1).id;
                }
                mRefreshLayout.setRefreshing(false);
            }
        }, 2000);
    }

    private void loadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                LogUtil.i("mLastID = " + mLastID);
                List<Photo> photos = PhotosList.instance().loadData(mLastID);
                mAdapter.addList(photos);
                mAdapter.setState(photos.size() >= APIConstant.PAGE_COUNT
                        ? BaseListAdapter.STATE_LOAD_MORE
                        : BaseListAdapter.STATE_NO_MORE);
                mLastID = photos.get(photos.size() - 1).id;
                LogUtil.i("photos.size() = " + photos.size());
                LogUtil.i("now mLastID = " + mLastID);
            }
        }, 2000);
    }

    private List<String> initMenu() {
        List<String> data = new ArrayList<String>();
        data.add("用户信息");
        data.add("设置");
        data.add("关于软件");

        return data;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        PhotoActivity.launch(this, mAdapter.getItem(position));
    }

    @Override
    public void onRefresh() {
        refreshData();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            if (mDrawerLayout.isDrawerOpen(mLeftDrawer)) {
                mDrawerLayout.closeDrawer(mLeftDrawer);
            } else {
                exit();
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onBackPressed() {
        if (mDrawerLayout.isDrawerOpen(mLeftDrawer)) {
            mDrawerLayout.closeDrawer(mLeftDrawer);
        } else {
            exit();
        }
    }

    private void exit() {
        if (System.currentTimeMillis() - mLastExitTime < 2000) {
            super.onBackPressed();
        } else {
            mLastExitTime = System.currentTimeMillis();
            super.shortToast(R.string.exit_app);
        }
    }

    @OnClick(R.id.avatar_view)
    protected void onAvatarViewClick() {
        try {
            User user = UserList.instance().get(LoginManager.instance().get());
            UserActivity.launch(this, user);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick(R.id.title_left_btn)
    protected void onTitleLeftClick() {
        if (mDrawerLayout.isDrawerOpen(mLeftDrawer)) {
            mDrawerLayout.closeDrawer(mLeftDrawer);
        } else {
            mDrawerLayout.openDrawer(mLeftDrawer);
        }
    }

    @OnClick(R.id.title_right_btn)
    protected void onTitleRightClick() {
        startActivity(new Intent(this, SearchActivity.class));
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            switch (position) {
                case 0:
                    break;
                case 1:
                    break;
                case 2:
                    break;
            }
        }
    }
}
